from django.shortcuts import render
import whisper
import zhconv

from web.views.chatbot.conversation_save import ConversationSave
from web.views.chatbot.chatbot_graph import ChatBotGraph

model = whisper.load_model("small")
con_save = ConversationSave()
handler = ChatBotGraph()


def get_yuyin(request):
    result = ""
    if request.method == "POST":
        # 获取请求参数
        yy = request.FILES.get('audio')
        import os
        with open(os.path.join('web/media', 'audio.wav'), 'wb') as fw:
            # 一次性读取文件
            # fw.write(yy.read())
            # 分块读取文件
            for w in yy.chunks():
                fw.write(w)
        # 至此 media 文件目录下已经有了名为 yy.name 的音频文件
        result = model.transcribe(os.path.join('web/media', 'audio.wav'), language='Chinese')
        result = zhconv.convert(result["text"], 'zh-hans')  # 繁体转简体
    if result and result != "":
        # 对send_Value进行处理，获取chatbot的回答
        con_save.addCon(result)
        response = handler.chat_main(result)
        con_save.addCon(response)
    else:
        response = "您好，我是寻医问药网站自动问答AI，希望可以帮到您。"
        if len(con_save.getlist()) == 0:
            con_save.addCon(response)

    result = con_save.getlist()
    context = {
        'response': result
    }
    return render(request, 'yuyin.html', context)
